import {isEmpty} from "../../../../utils/collectionUtils";



export function dispatchInSetup(dispatch, location){
  if(!dispatch){
    throw new Error("The dispatch should not be undefined")
  }

  if(!location || !location.query){
    throw new Error("The query of location should not be undefined")
  }

  dispatch({
    type: 'init',
    payload: {
      dispatch: dispatch
    }
  })
  dispatch({
    type: 'query',
    payload: {
      status: 2,
      ...location.query,
    },
  })
}

export function initInSetup(state, dispatch){
  initGridMenuAction(state, dispatch);
  initModalAction(state, dispatch);
  initPanelButtonAction(state, dispatch);
  return {
    ...state
  }
}



function initGridMenuAction(state, dispatch) {
  state.gridActionOptions = {
    menuClickHandler: (headerName, record, action) => {
      dispatch({
        type: "showModal",
        payload: {
          headerName: headerName,
          record: record,
          action: action
        },
      })
    }
  }
}

function initModalAction (state, dispatch) {
  state.modalOptions.actionOptions = {
    hideModal: () => {
      dispatch({
        type: "hideModal"
      })
    }
  }
}

function initPanelButtonAction (state, dispatch) {
  if(!state.panelOptions){
    return;
  }

  if(isEmpty(state.panelOptions.buttons)){
    return;
  }

  state.panelOptions.buttons.forEach((buttonConfig)=>{
    initEachButtonAction(buttonConfig, dispatch)
  })
}

function initEachButtonAction(buttonConfig, dispatch){
  if(!buttonConfig || !buttonConfig.name || !dispatch){
    return
  }


  switch(buttonConfig.name) {
    case "Create":
      buttonConfig.clickHandler = () => {
        dispatch({
          type: "showModalToCreate",
        })
      };
      break;
    default: return;
  }
}
